#include <fcntl.h>
#include <iostream>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>

using namespace std;

int main()
{
	// 以O_APPEND选项打开文件
	int fd = open( "file.txt", O_RDWR | O_APPEND );
	
	if( fd == -1 )
	{
		cout << "File open error: " << strerror(errno) << endl;
		return 0;
	}

    cout << "Step 1: " << "Print current file offset! " << endl;
	// 打印出当前的文件偏移量
	off_t CurrentPosition = lseek( fd, 0, SEEK_CUR );
	if( CurrentPosition == -1 )
	{
		cout << "Lseek error: " << strerror(errno) << endl;
		close(fd);
		return 0;
	}
    cout << "File offset position before the update operation: " << CurrentPosition << endl;


    cout << endl << "Step 2: " << "Modify the file offset!" << endl;
	// 修改当前文件偏移量为另外一个值
	off_t NewCurrentPosition = lseek( fd, 10, SEEK_CUR );
	if( NewCurrentPosition == -1 )
	{
		cout << "Lseek error: " << strerror(errno) << endl;
		close(fd);
		return 0;
	}
    cout << "File offset position after the update operation: " << NewCurrentPosition << endl;

    cout << endl << "Step 3: " << "Print the file offset before read operation!" << endl;
    cout << "File offset position before the read operation: " << NewCurrentPosition << endl;

    
    cout << endl << "Step 4: " << "Read some data from the file!" << endl;
    // 从文件中读取一定长度的字节, 并保存于buf字符数组中
	char buf[5];
	ssize_t len = read( fd, buf, 5 );
	if( len < 0 )
	{
		cout << "Read error: " << strerror(errno) << endl;
		close(fd);
		return 0;
	}
	buf[len] = '\0';
	cout << "Read specific-sized(5 Bytes) data from file: " << buf << endl;

    cout << endl << "Step 5: " << "Print the file offset after read operation!" << endl; 
    // 获取当前的文件偏移量
    off_t ReadAfterPosition = lseek( fd, 0, SEEK_CUR );
    if( ReadAfterPosition == -1 )
    {
        cout << "Lseek error: " << strerror(errno) << endl;
        close(fd);
        return 0;
    }
    cout << "File offset position after the read operation: " << ReadAfterPosition << endl;

	close(fd);
	return 0;
}
